const { getlist, detail, create, update } = require("../model/topic");
const { followingTopicUsers } = require("../model/user");
const { isObjectId } = require("../utils/validate");
const { getselects } = require("../utils/getselects");
// 获取话题列表
const List = async (ctx) => {
    let { keywords = "", page = 1, size = 10 } = ctx.query;
    size = Math.max(1, size);
    page = Math.max(1, page * 1) - 1;
    const list = await getlist(keywords, size, page);
    ctx.body = {
        code: 200,
        msg: "话题列表获取成功",
        data: list,
    };
};

// 获取话题详情
const Detail = async (ctx) => {
    const { id } = ctx.params;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "话题ID不合法",
            data: null,
        });
    }
    const selects = getselects(ctx.query.fields);
    const topic = await detail(id, selects);
    ctx.body = {
        code: 200,
        msg: "话题详情获取成功",
        data: topic,
    };
};

// 创建话题
const Create = async (ctx) => {
    const { name, avatar = "", introduction = "" } = ctx.request.body;
    if (!name) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "话题名称不能为空",
            data: null,
        });
    }
    const topic = await create({ name, avatar, introduction });
    ctx.body = {
        code: 200,
        msg: "话题创建成功",
        data: topic,
    };
};

// 更新话题
const Update = async (ctx) => {
    const { id } = ctx.params;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "话题ID不合法",
            data: null,
        });
    }
    const detail = await detail(id);
    if (!detail) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "话题不存在",
            data: null,
        });
    }
    const topic = await update(id, ctx.request.body);
    ctx.body = {
        code: 200,
        msg: "话题更新成功",
        data: topic,
    };
};

// 关注某个话题的用户列表
const FollowingTopicUsers = async (ctx) => {
    const { id } = ctx.params;
    if (!isObjectId(id)) {
        ctx.status = 400;
        return (ctx.body = {
            code: 400,
            msg: "话题ID不合法",
            data: null,
        });
    }
    const users = await followingTopicUsers(id);
    ctx.body = {
        code: 200,
        msg: "话题关注用户列表获取成功",
        data: users,
    };
};

module.exports = {
    List,
    Detail,
    Create,
    Update,
    FollowingTopicUsers,
};
